﻿using System.Diagnostics;
using UnityEngine;

namespace HEFramework
{
    /// <summary>
    ///
    /// UI画布行为基类
    /// 
    /// ----------------------------------------
    /// 作者：pan
    /// 创建时间：2021-04-01 01:56:26
    /// ----------------------------------------
    /// </summary>
    [RequireComponent(typeof(Canvas))]
    public class UICanvasBehaviourBase : MonoBehaviour, IUICanvasBehaviour
    {
        /// <summary>
        /// 画布
        /// </summary>
        protected Canvas canvas;

        /// <summary>
        /// 画布组（value为0关闭  1为开启）
        /// </summary>
        protected CanvasGroup canvasGroup;


        public Canvas Canvas
        {
            get => canvas;
        }

        public CanvasGroup CanvasGroup
        {
            get => canvasGroup;
        }


        /// <summary>
        /// 初始化
        /// </summary>
        public void Awake()
        {
            canvas = GetComponent<Canvas>();
            canvasGroup = GetComponent<CanvasGroup>();
            if (canvas == null)
            {
                canvas = gameObject.AddComponent<Canvas>();
            }

            if (canvasGroup == null)
            {
                canvasGroup = gameObject.AddComponent<CanvasGroup>();
            }
        }

        public IUICanvasBehaviour SetOrder(int _order)
        {
            canvas.sortingOrder = _order;
            return this;
        }

        public IUICanvasBehaviour SetCamera(Camera _camera)
        {
            canvas.worldCamera = _camera;
            return this;
        }

        public Transform GetTransform()
        {
            return canvas.transform;
        }
        
        /// <summary>
        /// 返回对象
        /// </summary>
        /// <returns></returns>
        public GameObject GetGameObject()
        {
            return canvas.gameObject;
        }

        /// <summary>
        /// 打开UI
        /// </summary>
        public IUICanvasBehaviour Open()
        {
            canvasGroup.alpha = 1;
            canvasGroup.blocksRaycasts = true;
            NameChange(true);
            return this;
        }

        /// <summary>
        /// 关闭UI
        /// </summary>
        public IUICanvasBehaviour Close()
        {
            canvasGroup.alpha = 0;
            canvasGroup.blocksRaycasts = false;
            NameChange(false);
            return this;
        }

        [Conditional("DEBUG_SHOW")]
        private void NameChange(bool _active)
        {
            string o = "[Open]";
            string c = "[Close]";
            this.gameObject.name = this.gameObject.name.Replace(o, "").Replace(c, "");
            if (_active)
            {
                this.gameObject.name = this.gameObject.RS() + o;
            }
            else
            {
                this.gameObject.name = this.gameObject.RS() + c;
            }
        }
    }
}